package com.iMusic.presentationLayer;

import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.iMusic.businessLogicLayer.Account;
import com.iMusic.businessLogicLayer.Address;
import com.iMusic.util.UserMessages;

public class CreateAccount extends HttpServlet {

	/*
	 * Create Account
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Account account = new Account();
		String redirection = "default.jsp";
		
		HttpSession session = request.getSession();
		
		account.setUsername((String) request.getParameter("username"));
		account.setPasswd((String) request.getParameter("password"));
		account.setName((String) request.getParameter("name"));
		account.setSex((String) request.getParameter("sex"));
		
		String birthdayStr = (String) request.getParameter("birthday");
		if (birthdayStr != null && !birthdayStr.equals(""))
			account.setBirthday( Date.valueOf(birthdayStr));
		account.setEmail((String) request.getParameter("email"));
		account.setVip("off");
		account.setFinancialInstitution((String) request.getParameter("financialInstitution"));
		account.setCreditDirect((String) request.getParameter("creditDirect"));
		account.setAccountNumber((String) request.getParameter("accountNumber"));
		String expiryDateStr = (String) request.getParameter("expiryDate");
		if (expiryDateStr != null && !expiryDateStr.equals(""))
			account.setExpiryDate(Date.valueOf(expiryDateStr));

		Address address = new Address();
		address.setStreet( (String) request.getParameter("street")) ;
		address.setStreetNbr( (String) request.getParameter("streetNbr")) ;
		address.setComplement( (String) request.getParameter("complement")) ;
		address.setCity( (String) request.getParameter("city")) ;
		address.setProvince( (String) request.getParameter("province")) ;
		address.setPostalCode( (String) request.getParameter("postalCode")) ;
		address.setCountry( (String) request.getParameter("country")) ;

		account.setAddress(address);
		
		try {
			account.createAccount();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			if (account.login()) {
				session.setAttribute("Account", account);
				System.out.println("User " + account.getUsername() + " logged in.");
				
			}
			else {
				redirection += "?error="+UserMessages.LOGIN_NOK;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		response.sendRedirect(redirection);
		
	}
}
